package xyz.xtt.exchange.service.impl;

import static xyz.xtt.common.asset.AssertUtils.isTrue;

import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.hutool.core.collection.CollectionUtil;
import xyz.xtt.exchange.constants.ErrorMessage;
import xyz.xtt.exchange.entity.TblAssetCopyright;
import xyz.xtt.exchange.mapper.TblAssetCopyrightMapper;
import xyz.xtt.exchange.request.CopyrightRequest;
import xyz.xtt.exchange.service.ITblAssetCopyrightService;
import xyz.xtt.exchange.service.ITblMerchantInfoService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author daveafei
 * @since 2025-03-18
 */
@Service
public class TblAssetCopyrightServiceImpl extends ServiceImpl<TblAssetCopyrightMapper, TblAssetCopyright> implements ITblAssetCopyrightService {

	@Autowired
	private TblAssetCopyrightMapper tblAssetCopyrightMapper;
	@Autowired
	private ITblMerchantInfoService iTblMerchantInfoService;

	@Override
	public Boolean saveCopyright(Long id, String uid, Integer copyrightType, List<String> copyrights) {
		if (CollectionUtil.isEmpty(copyrights)) {
			return Boolean.FALSE;
		}
		TblAssetCopyright tblAssetCopyright = new TblAssetCopyright();
		tblAssetCopyright.setAssetId(id);
		tblAssetCopyright.setAppUserId(Long.valueOf(uid));
		tblAssetCopyright.setCopyrightType(copyrightType);
		tblAssetCopyright.setCopyrightInfo(JSONObject.toJSONString(copyrights));
		return tblAssetCopyrightMapper.insert(tblAssetCopyright) > 0;
	}

	@Override
	public Boolean saveCopyright(CopyrightRequest copyrightRequest) {
		String uid = copyrightRequest.getUid();
		Long assetId = copyrightRequest.getAssetId();
		Long rootAssetId = copyrightRequest.getRootAssetId();
		String authorId = copyrightRequest.getAuthorId();
		List<String> copyrights = copyrightRequest.getCopyrights();
		List<String> originalCopyrights = copyrightRequest.getOriginalCopyrights();
		if (checkFirstBusiness(uid, rootAssetId, assetId, authorId)) {
			if (checkPersonal(uid)) {
				// 是个人
				isTrue(CollectionUtil.isEmpty(copyrights) && CollectionUtil.isEmpty(originalCopyrights), ErrorMessage.COPYRIGHT_ORIGINAL_CANNOT_BE_EMPTY);
			} else {
				isTrue(CollectionUtil.isEmpty(copyrights), ErrorMessage.COPYRIGHT_CANNOT_BE_EMPTY);
			}
			// 如果是商家 版权证明必填
			// 如果是个人 至少要填一个类型
			saveCopyright(assetId, uid, 0, copyrights);
			saveCopyright(assetId, uid, 1, originalCopyrights);
		}
		return Boolean.TRUE;
	}

	private Boolean checkFirstBusiness(String uid, Long rootAssetId, Long assetId, String authorId) {
		return Objects.equals(assetId, rootAssetId) && Objects.equals(authorId, uid);
	}

	private Boolean checkPersonal(String uid) {
		return !iTblMerchantInfoService.judgeMerchantPer(uid);
	}
}
